package min3d.sampleProject1;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

import android.util.Log;

public class TrackerThread extends Thread{
	DatagramSocket datagramSocket;
	DatagramPacket recvPacket;
	DatagramPacket draw1, draw2, not1, not2;
	InetAddress target;
	String server = "rubble.ucsd.edu";
	MyActivity ra;
	MyMenu myMenu;
	byte[] recvMsg = new byte[1024];
	int port = 44444;

	/**
	 * TrackerThread constructor. It is called in MyMenu.
	 * Instantiates the four possible datagrams after opening a connection.
	 * @param  MyMenu 				The MyMenu context from which it was called.
	 * @param  MyActivity				A handle to the MyActivity object. 
	 */
	public TrackerThread(MyMenu myMenu, MyActivity ra) {
		this.myMenu = myMenu;
		this.ra = ra;
		try {
			target = InetAddress.getByName(server);
			this.datagramSocket = new DatagramSocket();
			this.datagramSocket.setSoTimeout(500);
			draw1 = new DatagramPacket("1draw".getBytes(), 5, target, port);
			draw2 = new DatagramPacket("2draw".getBytes(), 5, target, port);
			not1 = new DatagramPacket("1not".getBytes(), 4, target, port);
			not2 = new DatagramPacket("2not".getBytes(), 4, target, port);
			this.recvPacket = new DatagramPacket(recvMsg, recvMsg.length);
		} catch (Exception e) {
			Log.e("TNET", "ERROR: "+e.toString());
		}
	}

	/**
	 * The Thread hook run.
	 * Contains a while loop that continuously sends and receives packets
	 * and sets the trackerLocation accordingly.
	 * @return void
	 */
	@Override
	public void run() {
		try {
			while (true) {
				long start = System.currentTimeMillis();
				
				//Log.v("TNET", "Run tracker thread");
				if(myMenu.tracker1 & ra.touchDown)	
					//this.datagramSocket.send(new DatagramPacket("1draw".getBytes(), 5, target, port));
					this.datagramSocket.send(draw1);
				else if(myMenu.tracker2 & ra.touchDown)	
					//this.datagramSocket.send(new DatagramPacket("2draw".getBytes(), 5, target, port));
					this.datagramSocket.send(draw2);
				else if(myMenu.tracker1 & !ra.touchDown)	
					//this.datagramSocket.send(new DatagramPacket("1not".getBytes(), 4, target, port));
					this.datagramSocket.send(not1);
				else if(myMenu.tracker2 & !ra.touchDown)	
					//this.datagramSocket.send(new DatagramPacket("2not".getBytes(), 4, target, port));
					this.datagramSocket.send(not2);
				
				this.datagramSocket.receive(recvPacket);
				MyActivity.trackerLocation = new String(recvMsg, 0, recvPacket.getLength());
				//Log.v("TNET", "ERROR: "+MyActivity.trackerLocation);
				
				long end = System.currentTimeMillis();
				String t = (end-start)+"";
				Log.v("TIMER", t);
			}
		} catch (SocketTimeoutException e){
			run();
		} catch (Exception e) {
			Log.e("TNET", e.toString());
		}
	}
}
